package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.repository.CartRepository;
import cn.edu.tju.elm.repository.FoodRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name = "管理购物车", description = "对购物车内的商品增删改查")
public class CartController {
    @Autowired
    private UserService userService;
    @Autowired
    private FoodRepository foodRepository;
    @Autowired
    private CartRepository cartRepository;

    @PostMapping("/carts")
    @Operation(summary = "添加商品到购物车")
    public HttpResult<Cart>  addCartItem(@RequestBody Cart cart){
        try {
            // 获取当前用户
            User user = userService.getUserWithAuthorities().get();
            // 检查商品是否存在
            Food food = foodRepository.findById(cart.getFood().getId()).orElse(null);
            if (food == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商品不存在");
            }

            // 检查是否已存在相同的购物车项（同一用户、同一商家、同一商品）
            Cart existingCart = cartRepository.findByCustomerIdAndBusinessIdAndFoodId(
                user.getId(), 
                food.getBusiness().getId(), 
                food.getId()
            );

            Cart savedCart;
            if (existingCart != null) {
                // 如果已存在，更新数量
                existingCart.setQuantity(existingCart.getQuantity() + cart.getQuantity());
                existingCart.setUpdateTime(LocalDateTime.now());
                savedCart = cartRepository.save(existingCart);
            } else {
                // 如果不存在，创建新的购物车项
                Cart newCart = new Cart();
                newCart.setDeleted(false);
                newCart.setFood(food);
                newCart.setQuantity(cart.getQuantity());
                newCart.setCustomer(user);
                newCart.setBusiness(food.getBusiness());
                newCart.setCreateTime(LocalDateTime.now());
                newCart.setUpdateTime(LocalDateTime.now());
                savedCart = cartRepository.save(newCart);
            }

            return HttpResult.success(savedCart);

        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "系统错误");
        }
    }

    @GetMapping ("/carts")
    @Operation(summary = "查询购物车中的商品和数量")
    public HttpResult<List<Cart>> getCartByUserIdAndBusinessId(@RequestParam(name = "business", required = false) Long businessId,
                                                        @RequestParam(name = "user", required = false) Long userId){



//       // 获取当前登录用户（优先使用当前用户，如果未传入userId）
//            User user = userService.getUserWithAuthorities().get();
//
//            List<Cart> cartItems;
//
//            if (businessId != null) {
//                // 查询指定用户和指定店铺的购物车商品
//                cartItems = cartRepository.findByCustomerIdAndBusinessIdWithFood(userId, businessId);
//            } else {
//                // 查询指定用户的所有购物车商品
//                cartItems = cartRepository.findByCustomerIdWithFood(userId);
//            }
//
//            // 直接返回Cart对象，包含商品信息和数量
//            return HttpResult.success(cartItems);

        // 1. 获取当前用户（优先使用参数中的userId）
        Long targetUserId = (userId != null) ? userId :
                userService.getUserWithAuthorities()
                        .map(User::getId)
                        .orElseThrow(() -> new RuntimeException("用户未登录"));

        // 2. 使用新List接收查询结果（确保隔离）
        List<Cart> cartItems = new ArrayList<>();

        if (businessId != null) {
            cartItems.addAll(cartRepository.findByCustomerIdAndBusinessIdWithFood(targetUserId, businessId));
        } else {
            cartItems.addAll(cartRepository.findByCustomerIdWithFood(targetUserId));
        }

        // 3. 返回不可变List（防止外部修改）
        return HttpResult.success(Collections.unmodifiableList(cartItems));

    }

    @PutMapping("/carts")
    @Operation(summary = "更新购物车商品数量")
    public HttpResult<Cart> updateCartItem(@RequestBody Cart cart) {
        try {
            // 获取当前用户
            User user = userService.getUserWithAuthorities().get();
            // 检查商品是否存在
            Food food = foodRepository.findById(cart.getFood().getId()).orElse(null);
            if (food == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "商品不存在");
            }

            // 查找现有的购物车项
            Cart existingCart = cartRepository.findByCustomerIdAndBusinessIdAndFoodId(
                user.getId(), 
                food.getBusiness().getId(), 
                food.getId()
            );

            if (existingCart == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "购物车项不存在");
            }

            // 更新数量
            existingCart.setQuantity(cart.getQuantity());
            existingCart.setUpdateTime(LocalDateTime.now());
            
            Cart savedCart = cartRepository.save(existingCart);
            return HttpResult.success(savedCart);

        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "系统错误");
        }
    }

    @DeleteMapping("/carts")
    @Operation(summary = "删除购物车商品")
    public HttpResult<String> removeCartItem(@RequestParam Long foodId, @RequestParam Long businessId) {
        try {
            // 获取当前用户
            User user = userService.getUserWithAuthorities().get();

            // 查找现有的购物车项
            Cart existingCart = cartRepository.findByCustomerIdAndBusinessIdAndFoodId(
                user.getId(), 
                businessId, 
                foodId
            );

            if (existingCart == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "购物车项不存在");
            }

            // 删除购物车项
            cartRepository.delete(existingCart);
            return HttpResult.success("删除成功");

        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SYSTEM_ERROR, "系统错误");
        }
    }
}





